package com.parking.common.web.exception;

import com.parking.common.core.exception.ParkingException;
import com.parking.common.core.model.Result;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.springframework.validation.BindException;
import java.security.SignatureException;


@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(ParkingException.class)
    public Result parkingExceptionHandler(ParkingException e){
        e.printStackTrace();
        return Result.getResult().setCode(e.getCode()).setMessage(e.getMessage()).setFlag(false);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException e){
        e.printStackTrace();
        return Result.getResult().setMessage("参数格式错误(多半是时间参数)").setFlag(false);
    }

    @ExceptionHandler({MalformedJwtException.class,SignatureException.class, ExpiredJwtException.class})
    public Result jwtException(Exception e) throws Exception {
        e.printStackTrace();
        return Result.getResult().setCode(500).setMessage("token无效或已过期").setFlag(false);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        return Result.getResult().setCode(500).setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage()).setFlag(false);
    }

    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException e){
        e.printStackTrace();
        return Result.getResult().setCode(500).setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage()).setFlag(false);
    }

    @ExceptionHandler(Throwable.class)
    public Result systemHandler(Throwable e){
        e.printStackTrace();
        return Result.getResult().setCode(500).setMessage("系统异常").setFlag(false);
    }
}
